package com.example.test.service;

import com.example.test.bean.domain.ShopUser;
import com.example.test.exception.BusinessException;
import com.example.test.mapper.ShopUserMapper;
import com.example.test.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class ShopUserService {

	@Autowired
	private ShopUserMapper shopUserMapper;

	@Autowired
	private PasswordEncoder passwordEncoder;

	public ShopUser register(String mobile, String password, String nickname) {
		if (shopUserMapper.findByMobile(mobile) != null) {
			throw new BusinessException(401, "手机号已注册");
		}

		ShopUser user = new ShopUser();
		user.setMobile(mobile);
		user.setPassword(passwordEncoder.encode(password));
		user.setNickname(nickname);
		shopUserMapper.insertUser(user);
		user.setPassword("");
		return user;
	}

	public Map<String, Object> login(String mobile, String password) {
		ShopUser user = shopUserMapper.findByMobile(mobile);
		if (user == null || !passwordEncoder.matches(password, user.getPassword())) {
			throw new BusinessException(402, "手机号或密码错误");
		}
		// 生成 Token
		String token = JwtUtil.generateToken(mobile, user.getId());

		// 返回 User + Token
		Map<String, Object> response = new HashMap<>();
		response.put("token", token);
		response.put("user", user);
		response.put("password", "");
		return response;
	}

	public void changePassword(Integer userId, String oldPassword, String newPassword) {
		ShopUser user = shopUserMapper.findById(userId);
		if (user == null || !passwordEncoder.matches(oldPassword, user.getPassword())) {
			throw new BusinessException(403, "旧密码错误");
		}
		user.setPassword(passwordEncoder.encode(newPassword));
		shopUserMapper.updateUser(user);
	}
}
